﻿<!-- 工装传感器挑选/扫码 -->

<template>
  <!-- 工装列表 -->
  <div style="min-height: 150px; display: flex; align-items: center; justify-content: center">
    <el-button v-if="toolCards.length <= 0" type="primary" :icon="Setting" @click="handleToolSettingOpen">
      工装设置
    </el-button>
    <el-scrollbar v-else ref="refScrollbar" @wheel.prevent="handleHorScroll">
      <div style="display: inline-flex">
        <ToolSensorsCard
          v-for="tool in toolCards"
          :key="tool.toolCode"
          class="mr-3 mb-3"
          :is-edit-mode="true"
          :tool-data="tool"
          @tool-setting-click="handleToolSettingOpen"
        />
      </div>
    </el-scrollbar>
  </div>
  <!-- 工装列表 End -->

  <el-card shadow="never">
    <el-tabs tab-position="left" style="height: 300px" class="demo-tabs">
      <!-- 仪器挑选 -->
      <el-tab-pane label="仪器挑选">
        <!-- 搜索及Table区域 -->
        <el-row :gutter="5">
          <el-col :span="2">仪器编码</el-col>
          <el-col :span="4">
            <el-input v-model="paramSensorCode" />
          </el-col>
          <el-col :span="2">日期</el-col>
          <el-col :span="10">
            <el-date-picker
              v-model="paramDataRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-col>
          <el-col :span="2.5">
            <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          </el-col>
          <!--          <el-col :span="2.5">
            <el-button type="primary" icon="Plus" @click="">
              {{ selectedToolName }}
            </el-button>
          </el-col>-->
        </el-row>

        <!-- 列表 -->
        <el-table
          v-loading="loading"
          border
          stripe
          height="250px"
          :data="sensorStore.pendingSensorData"
          highlight-current-row
          class="data-table__content"
        >
          <!--          <el-table-column type="selection" />-->
          <el-table-column label="序号" width="55px" type="index" align="center" />
          <el-table-column
            label="仪器编码"
            width="200px"
            :show-overflow-tooltip="true"
            align="center"
            prop="sensorCode"
          />
          <el-table-column
            label="仪器名称"
            align="center"
            :show-overflow-tooltip="true"
            prop="sensorName"
          />
          <el-table-column label="型号" align="center" prop="sensorMode" />
          <el-table-column
            label="送检单位"
            align="center"
            :show-overflow-tooltip="true"
            prop="submitUnit"
          />
          <el-table-column
            label="送检日期"
            :show-overflow-tooltip="true"
            align="center"
            prop="submitDate"
          />
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="scope">
              <el-popover
                :width="230"
                v-if="!scope.row.isSelected"
                placement="right"
                title="选择对应插槽"
                trigger="hover"
              >
                <template #reference>
                  <el-button type="primary" icon="Plus" link>
                    {{ selectedToolName }}
                  </el-button>
                </template>
                <ToolSlotSensorBind :sensor-info="scope.row" />
              </el-popover>

              <el-tag v-if="scope.row.isSelected" effect="light" type="info">已添加</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <!-- 列表 end -->
      </el-tab-pane>
      <!-- 仪器挑选 End -->
      <!-- 扫码添加 -->
      <el-tab-pane label="扫码添加">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-input
              v-model="txtScanInput"
              type="textarea"
              :rows="13"
              placeholder="光标置于输入框内，即可开始扫码。"
              @input="handleScanTxtChange"
            />
          </el-col>
          <el-col :span="16">
            <el-table
              table-layout="auto"
              height="300px"
              :row-class-name="scanLogRowClassName"
              :show-header="false"
              :data="scanLogs"
            >
              <el-table-column label="时间" prop="time" />
              <el-table-column label="消息" prop="msg" />
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- 扫码添加 End -->
    </el-tabs>
  </el-card>

  <!-- 工装工位绑定 Drawer -->
  <el-drawer v-model="drawerVisible" title="📄工装设置" direction="rtl">
    <tool-station-set />
  </el-drawer>
  <!-- 工装工位绑定 End -->
</template>

<script setup lang="ts">
import { useSensorStore } from "@/store/business/sensor.store";
import ToolSensorsCard from "@/views/business/sensor/components/ToolSensorsCard.vue";
import SensorAPI from "@/api/business/sensor.api";
import { format } from "date-fns";
import { ElementTypeEnum } from "@/enums";
import { Setting } from "@element-plus/icons-vue";
import { useSettingsStore } from "@/store";
import ToolStationSet from "@/views/business/sensor/components/ToolStationSet.vue";
import ToolSlotSensorBind from "@/views/business/sensor/components/ToolSlotSensorBind.vue";

const sensorStore = useSensorStore();
const settingStore = useSettingsStore();

const loading = ref(false);
const paramSensorCode = ref("");
const paramDataRange = ref("");

const selectedToolName = computed(() => sensorStore.currentToolInfo?.toolName ?? "");

// 工装数据，监听sensorStore.allTools
const toolCards = ref<ToolInfo[]>([]);
watch(
  sensorStore.allTools,
  (vals: ToolInfo[]) => {
    toolCards.value = vals
      .filter((tool) => tool.stationNum > 0)
      .sort((a, b) => a.stationNum - b.stationNum);
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  handleQuery();
});

function handleQuery() {
  const searchParam = {
    sensorCode: paramSensorCode.value,
    startDate: paramDataRange.value ? paramDataRange.value[0] : "",
    endDate: paramDataRange.value ? paramDataRange.value[1] : "",
  };
  sensorStore.loadSensorData(searchParam);
}

function handleAddSensor(sensor: SensorInfo | SensorInfo[]) {
  sensorStore.addSelectedSensors(sensor);
}

const refScrollbar = ref(null);
function handleHorScroll(e: any) {
  const wheelDelta = e.wheelDelta || -e.deltaY * 40;
  refScrollbar.value.setScrollLeft(refScrollbar.value.wrapRef.scrollLeft - wheelDelta);
}

// region 工装-工位绑定相关

const drawerVisible = ref(false);

/**
 * 打开工装-工位绑定页
 */
function handleToolSettingOpen() {
  drawerVisible.value = true;
}

// endregion

// region 扫码相关

const txtScanInput = ref<string>("");
function handleScanTxtChange() {
  // 判断最后一个字符是否为回车符
  if (txtScanInput.value.charAt(txtScanInput.value.length - 1) !== "\n") return;

  if (settingStore.elementType !== ElementTypeEnum.Rain && !sensorStore.currentToolCode) {
    raiseScanLog("warning", `请先选择工装/托盘`);
    return;
  }

  // 获取最后一行的内容
  const lastLine = txtScanInput.value.trimEnd().split("\n").pop().trim();
  if (!lastLine) return;
  SensorAPI.getPendingSensors({ sensorCode: lastLine }).then((res) => {
    if (res && res.length > 0) {
      const firstItem = res[0];
      const isSelected = sensorStore.isAlreadySelected(firstItem.sensorCode);
      if (isSelected) {
        raiseScanLog("warning", `此仪器（${firstItem.sensorCode}）已被添加。`);
        return;
      }
      const selectedSensor: SensorInfo = { ...firstItem };
      sensorStore.addSelectedSensors(selectedSensor);
      raiseScanLog("success", `仪器（${firstItem.sensorCode}）添加成功。`);
    } else {
      raiseScanLog("error", `待检仪器列表中未找到此仪器（${lastLine}）`);
    }
  });
}

const scanLogs = ref<{ type: string; time: string; msg: string }[]>([]);
const scanLogRowClassName = ({ row }: { row: { type: string; time: string; msg: string } }) => {
  if (row.type === "success") {
    return "success-row";
  }
  if (row.type === "warning") {
    return "warning-row";
  }
  if (row.type === "error") {
    return "error-row";
  }
};
function raiseScanLog(type: string, msg: string) {
  scanLogs.value.unshift({
    type,
    time: format(new Date(), "yyyy-MM-dd HH:mm:ss"),
    msg,
  });
  ElMessage({
    message: msg,
    type,
  });
}
// endregion
</script>

<style scoped lang="scss">
:deep(.error-row) {
  --el-table-tr-bg-color: var(--el-color-danger-light-8);
}
:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-8);
}
:deep(.success-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-8);
}
</style>
